package daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import utility.Utility;
import dao.CategoryDAO;
import domain.Category;

public class CategoryDaoImpl implements CategoryDAO {
	protected static Logger log = Logger.getLogger(CategoryDaoImpl.class);

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	@Override
	public void addCategory(Category category) {
		log.debug("Adding a new category ...");
		Session session = Utility.getSession();
		Transaction txn = session.beginTransaction();
		try {
			session.save(category);
			txn.commit();
			log.debug("Added new category!");
		} catch (Exception ex) {
			if (txn.isActive()) {
				txn.rollback();
			}
		} finally {
			session.close();
		}
	}

	@Override
	public void editCategory(Category category) {
		Session session = sessionFactory.getCurrentSession();
		Category existCategory = (Category) session.get(Category.class, category.getId());
		existCategory.setName(category.getName());
		existCategory.setProducts(category.getProducts());
		session.save(existCategory);
	}

	@Override
	public void disableCategory(Category category) {
		Session session = sessionFactory.getCurrentSession();
		category.setStatus("Y");
		session.save(category);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Category> searchCategory(String strSearch) {
		String sql = "FROM Category WHERE name like %:name%";
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(sql);
		query.setString("name", strSearch);
		return query.list();
	}

}
